package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type LogDrgDipService struct {
	repo repository.LogDrgDipRepository
}

func NewLogDrgDipService(repo repository.LogDrgDipRepository) *LogDrgDipService {
	return &LogDrgDipService{repo: repo}
}

func (s *LogDrgDipService) CreateLog(c *gin.Context) {
	var log model.LogDrgDip
	if err := c.ShouldBindJSON(&log); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.Create(&log); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, log)
}

func (s *LogDrgDipService) GetLogByID(c *gin.Context) {
	id := c.Param("id")
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	log, err := s.repo.GetByID(uint(idUint))
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, log)
}

func (s *LogDrgDipService) ListLogsByPatient(c *gin.Context) {
	patientNo := c.Param("patientNo")
	logs, err := s.repo.ListByPatient(patientNo)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, logs)
}

func (s *LogDrgDipService) ListLogsByDateRange(c *gin.Context) {
	hospitalCode := c.Param("hospitalCode")
	startDateStr := c.Query("startDate")
	endDateStr := c.Query("endDate")

	startDate, err := time.Parse("2006-01-02", startDateStr)
	if err != nil {
		c.JSON(400, gin.H{"error": "invalid start date format"})
		return
	}

	endDate, err := time.Parse("2006-01-02", endDateStr)
	if err != nil {
		c.JSON(400, gin.H{"error": "invalid end date format"})
		return
	}

	logs, err := s.repo.ListByHospital(hospitalCode, startDate, endDate)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, logs)
}
